﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace YasharEl.Infrastructure.Configuration
{
    public class ImplementorValidator<InterfaceType, ExceptionType>
        where InterfaceType : class
        where ExceptionType : InvalidSystemConfigurationException
    {
        public virtual void ValidateType(Type type, string configAttribute)
        {
            Contract.Requires<ArgumentNullException>(type != null, "type could not be null.");
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(configAttribute), "configAttribute could not be null or empty.");

            string message = string.Format(
                "{0} must be valid {1} implementor but in configuration file specified '{2}' type.", 
                configAttribute,
                typeof(InterfaceType).FullNameToString(),
                type
            );

            if (type.IsInterface || !typeof(InterfaceType).IsAssignableFrom(type))
            {
                ExceptionType exceptionToThrow = (ExceptionType)Activator.CreateInstance(
                    typeof(ExceptionType),
                    new object[] { message }
                );
                throw exceptionToThrow;
            }
        }
    }
}
